package com.fy.controller;


import cn.hutool.json.JSONUtil;
import com.fy.entity.Result;
import com.fy.entity.Software;
import com.fy.entity.Softwarev;
import com.fy.entity.User;
import com.fy.service.ISoftwareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.jws.soap.SOAPBinding;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 晓岩
 * @since 2022-06-11
 */
@RestController
@RequestMapping("/softw")
public class SoftwareController {
    @Autowired
    ISoftwareService softwareService;
    @Autowired
    RedisTemplate redisTemplate;
    @RequestMapping("add")
    public Result add(@RequestBody Software software){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(!(principal instanceof User)){
            return new Result(201,"","匿名用户不能提交");
        }
        User loginUser = (User)principal;
        if(!loginUser.getRole().equals("admin")){
            return new Result(200,"","只有管理员才能提交");
        }
        String digestAsHex = DigestUtils.md5DigestAsHex(JSONUtil.toJsonStr(software).getBytes(StandardCharsets.UTF_8));
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(digestAsHex, new Date(), 30, TimeUnit.MINUTES);
        if(!aBoolean){
            return new Result(202,"","表单不能重复提交");
        }
        boolean b = softwareService.saveOrUpdate(software);
        if(b){
            return new Result(200,"","保存成功");
        }else{
            return new Result(203,"","保存失败");
        }
    }
//    @RequestMapping("update")
//    public Result update(@RequestBody User user){
//        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        if(!(principal instanceof User)){
//            return new Result(201,"","匿名用户不能提交");
//        }
//        User loginUser = (User)principal;
//        if(!"admin".equals(loginUser.getRole())){
//            return new Result(202,"","只有管理员才能提交");
//        }
//        String digestAsHex = DigestUtils.md5DigestAsHex(JSONUtil.toJsonStr(user).getBytes(StandardCharsets.UTF_8));
//        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(digestAsHex, new Date(), 30, TimeUnit.MINUTES);
//        if(!aBoolean){
//            return new Result(203,"","表单不能重复提交");
//        }
//    }
}
